<?php

namespace common\util;

class CookieUtil
{
    /**
     * @var string
     */
    private static string $prefix = 'yijiantian_oa_';


    /**
     * 保存cookie，默认是7天
     *
     * @param string $name
     * @param array|string $value
     * @param int $expire
     * @param string $path
     * @param string $domain
     */
    public static function saveCookie(string $name, array|string $value, int $expire = 360, string $path = '/', string $domain = ''): void
    {
        $expireTime = time() + $expire * 3600 * 24;
        $name = explode(',', $name);

        if (!is_array($value)) {
            $value = explode(',', $value);
        }

        for ($i = 0; $i < count($value); $i++) {
            setcookie(self::$prefix . $name[$i], $value[$i], $expireTime, $path, $domain);
        }
    }

    /**
     * 获取cookie
     *
     * @param $name
     * @return array
     */
    public static function getCookie($name): array
    {
        $name = explode(',', $name);
        for ($i = 0; $i < count($name); $i++) {
            $value[$name[$i]] = self::cookie($name[$i]);
        }
        return $value;
    }


    /**
     * @param string $name
     * @param string $dev
     * @return mixed
     */
    public static function cookie(string $name, string $dev = ''): mixed
    {
        $value = '';
        $name = self::$prefix . $name;

        if (isset($_COOKIE[$name])) {
            $value = $_COOKIE[$name];
        }

        if (empty($value)) {
            $value = $dev;
        }

        return $value;
    }

    /**
     * 删除cookie
     *
     * @param string $name
     * @param string $path
     * @param string $domain
     */
    public static function clearCookie(string $name, string $path = '/', string $domain = ''): void
    {
        $name = explode(',', $name);
        for ($i = 0; $i < count($name); $i++) {
            setcookie(self::$prefix . $name[$i], '', time() - 1, $path, $domain);
            @$_COOKIE[$name[$i]] = '';
        }
    }

    /**
     * 删除所有cookie
     */
    public static function clearAllCookie(): void
    {
        foreach ($_COOKIE as $key => $value) {
            self::clearcookie($key);
        }
    }
}